/*
 * @Author: your name
 * @Date: 2022-03-17 17:18:11
 * @LastEditTime: 2022-04-06 19:28:13
 * @LastEditors: Please set LastEditors
 * @Description: 文章编辑主页
 * @FilePath: \blog-system-front\src\Pages\Article\writeArticle\index.js
 */
import React, { useState, useEffect } from "react";
import ContentHeader from "@/Containers/ContentHeader";
import Main from "@/Containers/main";
import Editor from "md-editor-rt";
import "md-editor-rt/lib/style.css";
import { Button, Form, Modal, notification, Result } from "antd";
import SaveForm from "./saveForm";
import { useSelector, connect } from "react-redux";
import request from "@/api";
import { fetchArticleDetail, updateArticle } from "@/Services/article";
function WriteArticle(props) {
  const { id } = props.match.params;
  const [isModalVisible, setModalVisible] = useState(false); // 保存弹窗
  const [text, setText] = useState(``); // 富文本默认展示内容
  const [categoryInfo, setCategortInfo] = useState([]); // 分类标签
  const [form] = Form.useForm();
  const [previewOnly, setPriviewOnly] = useState(id !== "new");
  const user = useSelector((state) => state.user);

  const handleCateInfo = (value) => {
    setCategortInfo(value);
  };
  useEffect(() => {
    fetchArticleDetail({
      articleId: id,
    }).then((res) => {
      setText(res.content[0].content);
      form.setFieldsValue({
        ...res.content[0],
      });
    });
  }, []);
  /**
   * @description: 博客保存处理
   * @param {*}
   * @return {*}
   */
  const handleSaveArticle = async () => {
    const category = categoryInfo.map((d) => d.category_name);
    const categoryId = categoryInfo.map((d) => d.category_id);
    await form.validateFields();
    if (text.length === 0) {
      notification.error({
        message: "请输入文章内容",
      });
      return false;
    }
    const submitData = {
      ...form.getFieldsValue(),
      categoryId,
      category,
      content: text,
      userId: user.userId,
      author: user.nickname,
      articleId: id,
    };
    if (id !== "new") {
      updateArticle(submitData).then((res) => {
        setModalVisible(false);
        props.history.push(`/checkout/success/${id}`);
      });
    } else {
      request({
        url: "/v1/article/list/save",
        method: "POST",
        data: submitData,
      }).then((res) => {
        if (!res.failed) {
          setModalVisible(false);
          props.history.push(`/checkout/success/${res.result.insertId}`);
        }
      });
    }
  };
  /**
   * @description: 富文本上传处理
   * @param {*} files
   * @param {*} callback
   * @return {*}
   */
  const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
      Array.from(files).map((file) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.append("file", file);

          request({
            url: "/v1/file-upload",
            method: "POST",
            data: form,
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
            .then((res) => rev(res))
            .catch((error) => rej(error));
        });
      })
    );
    callback(
      res.map((item) => {
        return item.url;
      })
    );
  };

  return (
    <>
      <ContentHeader
        title="文章编辑"
        backPath={id === "new" ? null : "/article/list"}
      >
        {id !== "new" && (
          <Button onClick={() => {
            if (!previewOnly) {
              setText(form.getFieldValue().content)
            }
            setPriviewOnly(!previewOnly)
          }}>
            {previewOnly ? "编辑" : "取消"}
          </Button>
        )}
        <Button
          onClick={() => setModalVisible(true)}
          style={{ marginRight: 10 }}
          type="primary"
        >
          发布文章
        </Button>
      </ContentHeader>
      <Main>
        {previewOnly ? (
          <Editor modelValue={text} previewOnly />
        ) : (
          <Editor
            modelValue={text}
            onChange={setText}
            onUploadImg={onUploadImg}
          />
        )}

        <Modal
          visible={isModalVisible}
          title="文章发布"
          width={550}
          onCancel={() => setModalVisible(false)}
          onOk={() => {
            handleSaveArticle();
          }}
        >
          <SaveForm
            form={form}
            categoryInfo={categoryInfo}
            setCategortInfo={handleCateInfo}
          ></SaveForm>
        </Modal>
      </Main>
    </>
  );
}
export default connect()(WriteArticle);
